<template>
  <el-dialog
    v-model="visible"
    width="640px"
    top="10vh"
    class="customer-add-dialog"
    destroy-on-close
    :show-close="false"
  >
    <template #header>
      <div class="dialog-header">
        <h3 class="title">📝 新建客户</h3>
        <p class="subtitle">请填写客户基本信息，便于后续跟进</p>
      </div>
    </template>
    <!-- Form -->
    <div class="form-card">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="form-wrap">
        <el-form-item label="" label-width="0">
          <div class="recognize-row">
            <el-input
              class="ocr-input"
              v-model="recognizeText"
              @enter.stop
              type="textarea"
              placeholder="粘贴收件人信息"
              rows="3"
            />
            <el-button class="ocr-btn" size="small" type="primary" @click="handleRecognize"
              >识别</el-button
            >
            <!-- 查看格式 -->
            <el-button
              class="ocr-btn-format"
              size="small"
              link
              type="primary"
              @click="showPreview = true"
              >查看格式</el-button
            >
          </div>
        </el-form-item>
        <div class="form-item-body">
          <el-form-item label="客户姓名" prop="customerName">
            <el-input
              v-model="form.customerName"
              placeholder="例:张伟"
              clearable
              class="input-enhanced"
            />
          </el-form-item>
          <el-form-item class="customer-phone" label="联系电话" prop="customerPhone">
            <el-input
              v-model="form.customerPhone"
              :maxlength="11"
              placeholder="11 位手机号"
              clearable
              class="input-enhanced"
            />
          </el-form-item>
          <el-form-item label="" prop="group">
            <template #label>
              <div style="display: flex; align-items: center">
                <el-space>
                  客户分组
                  <el-tooltip
                    content="如果遇到多个客户信息为同一个人，可以创建分组，关联客户信息。"
                    placement="top"
                  >
                    <el-image style="width: 12px; height: 12px" :src="txstatus"></el-image>
                  </el-tooltip>
                </el-space>
              </div>
            </template>
            <el-select v-model="form.group" filterable placeholder="请选择客户分组">
              <template #prefix>
                <el-tooltip content="添加客户分组" placement="top">
                  <el-button
                    class="add-group-button"
                    type="primary"
                    size="small"
                    @click.stop="handleAddGroup"
                    :icon="Plus"
                  />
                </el-tooltip>
              </template>

              <el-option
                v-for="item in customerTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 来源 -->
        <el-form-item label="客户来源" prop="customerSource">
          <el-select
            v-model="form.customerSource"
            placeholder="选择来源渠道"
            clearable
            class="input-enhanced"
            popper-class="select-popper-enhanced"
          >
            <el-option label="线上推广" value="baidu" />
            <el-option label="线下渠道" value="线下渠道" />
            <el-option label="转介绍" value="转介绍" />
          </el-select>
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="客户地址" prop="contactAddress">
          <el-input
            type="textarea"
            v-model="form.contactAddress"
            placeholder="省市区 + 详细地址"
            :rows="2"
            clearable
            class="input-enhanced"
          />
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注信息" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="如：偏好沟通时间、特殊需求等"
            :rows="3"
            clearable
            class="input-enhanced"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-image-viewer
      v-if="showPreview"
      :url-list="srcList"
      :initial-index="0"
      @close="showPreview = false"
    />

    <!-- Footer -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="hide" :disabled="saveLoading" class="btn-cancel"> 取消 </el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleSubmit" class="btn-submit">
          保存客户
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import {
  addCustomer,
  getCustomer,
  updateCustomer,
  updateCustomerSalesman
} from '../../api/customers';
import useUserStore from '../../store/modules/user';
import { addData } from '@/api/system/dict/data';
import { parseInfo } from '../../utils';
import strsl from '../../assets/images/strsl.png';
import { Plus } from '@element-plus/icons-vue';
import { useCustomStore } from '../../store/modules/custom';
import txstatus from '../../assets/images/txstatus.png';

interface CustomerForm {
  customerId: String | number;
  customerName: string;
  customerPhone: number | String;
  customerSource?: string;
  contactAddress?: string;
  group?: string;
  createBy?: string;
  remark?: string;
}

const visible = ref(false);
const showPreview = ref(false);
const srcList = [strsl];
const formRef = ref<FormInstance>();

const form = reactive<CustomerForm>({
  customerId: '',
  customerName: '',
  customerPhone: '',
  customerSource: '',
  contactAddress: '',
  group: '',
  createBy: '',
  remark: ''
});

const userApp = useUserStore();
const customStore = useCustomStore();
const customerTypes = computed(() => customStore.customerTypesOptions);

const emit = defineEmits(['ok']);

/** 校验规则 */
const rules: FormRules = {
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  customerPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  contactAddress: [{ required: true, message: '请输入客户地址', trigger: 'blur' }]
};

const recognizeText = ref('');
const handleRecognize = () => {
  if (!recognizeText.value) {
    ElMessage.warning('请先粘贴收件人信息');
    return;
  }

  const { name, phone, address } = parseInfo(recognizeText.value);
  form.customerName = name;
  form.customerPhone = phone;
  form.contactAddress = address;
};

const saveLoading = ref(false);
function handleSubmit() {
  formRef.value?.validate((valid) => {
    if (valid) {
      saveLoading.value = true;
      let result: Promise<any>;
      if (form.customerId) {
        result = updateCustomer({ ...form });
      } else {
        result = addCustomer({ ...form });
      }

      result
        .then(async (res) => {
          saveLoading.value = false;
          hide();
          // 如果是销售角色，自动分配给当前登录的业务员
          if (userApp.roles.includes('saleUser')) {
            await updateCustomerSalesman({
              customerId: res.data.customerId,
              salesmanId: userApp.id
            });
          }
          ElMessage.success('操作成功');
          emit('ok');
        })
        .finally(() => {
          saveLoading.value = false;
        });
    }
  });
}

// 处理添加客户分组
function handleAddGroup() {
  // 打开客户分组弹窗
  ElMessageBox.prompt('请输入客户分组名称', '客户分组名称', {
    confirmButtonText: '创建',
    cancelButtonText: '取消',
    // 非空判断
    inputPattern: /^\S+$/,
    inputErrorMessage: '请输入客户分组名称'
  })
    .then(({ value: dictLabel }) => {
      const dictType = 'custom_types';
      addData({
        dictType,
        dictLabel,
        dictValue: new Date().getTime().toString(),
        listClass: 'default',
        status: '0'
      }).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('客户分组添加成功');
          // 刷新字典缓存（关键！）
          customStore.getCustomerTypes();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled'
      });
    });
}

async function show(row: any) {
  resetForm();
  if (row.customerId) {
    await getCustomer(row.customerId).then(({ code, data }: any) => {
      if (code === 200) Object.assign(form, data);
    });
  }
  visible.value = true;
}
function hide() {
  visible.value = false;
}
function resetForm() {
  Object.keys(form).forEach((k) => ((form as any)[k] = ''));
  formRef.value?.clearValidate();
}

defineExpose({ show, hide });
</script>
<style lang="scss">
// ======== 主色调 & 变量 ========
$primary: #4361ee;
$primary-hover: #3a56d4;
$gray-light: #f8f9fa;
$gray: #adb5bd;
$text: #212529;
$border: #dee2e6;
$success: #4cc985;

.customer-add-dialog {
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.12);
  overflow: hidden;
  padding: 0 !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;

  .dialog-header {
    padding: 32px 40px 16px;
    border-bottom: 1px solid rgba($border, 0.6);
    background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);

    .title {
      margin: 0;
      font-size: 22px;
      font-weight: 700;
      color: $text;
      letter-spacing: -0.5px;
    }

    .subtitle {
      margin: 8px 0 0;
      font-size: 14px;
      color: $gray;
      font-weight: 500;
    }
  }

  .form-card {
    padding: 10px 30px;
    background-color: #fff;

    .recognize-row {
      display: flex;
      gap: 12px;
      align-items: flex-start;
      width: 100%;
      position: relative;

      .ocr-input {
        box-sizing: border-box;
      }

      .ocr-btn {
        position: absolute;
        bottom: 8px;
        right: 65px;
      }
      .ocr-btn-format {
        position: absolute;
        bottom: 8px;
        right: 5px;
      }
    }
  }

  .form-wrap {
    :deep(.el-form-item) {
      margin-bottom: 28px !important;

      .el-form-item__label {
        font-weight: 600;
        color: $text;
        font-size: 15px;
      }
    }

    .form-item-body {
      display: flex;

      .el-form-item {
        flex: 1;
      }

      .customer-phone {
        margin: 0 5px;
      }

      .el-select__wrapper {
        padding-left: 5px;
      }
    }
  }

  .input-enhanced {
    :deep(.el-input__wrapper),
    :deep(.el-textarea__inner) {
      border-radius: 12px !important;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid $border;
      transition: all 0.3s ease;

      &:hover {
        border-color: $primary;
        box-shadow: 0 2px 8px rgba($primary, 0.15);
      }

      &.is-focus {
        border-color: $primary;
        box-shadow: 0 0 0 3px rgba($primary, 0.15);
      }
    }

    :deep(.el-input__inner),
    :deep(.el-textarea__inner) {
      font-size: 15px;
      color: $text;
    }
  }

  .add-group-button {
    padding: 8px;
  }

  // ======== 增强 Select 下拉 ========
  :deep(.select-popper-enhanced) {
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
    font-size: 15px;

    .el-select-dropdown__item {
      padding: 10px 20px;
      height: auto;
      line-height: 1.5;
    }
  }

  // ======== 底部按钮 ========
  .dialog-footer {
    padding: 24px 40px;
    display: flex;
    justify-content: center;
    gap: 16px;
    background: $gray-light;
    border-top: 1px solid rgba($border, 0.4);

    .el-button {
      padding: 10px 28px;
      border-radius: 10px;
      font-weight: 600;
      font-size: 15px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      transition: all 0.2s ease;
    }

    .btn-cancel {
      background: #fff;
      border: 1px solid $border;
      color: $text;

      &:hover:not([disabled]) {
        background: #f1f3f5;
        color: $text;
        transform: translateY(-1px);
      }
    }

    .btn-submit {
      background: linear-gradient(135deg, $primary 0%, $primary-hover 100%);
      border: none;
      box-shadow: 0 4px 12px rgba($primary, 0.3);

      &:hover:not([loading]) {
        transform: translateY(-1px);
        box-shadow: 0 6px 16px rgba($primary, 0.35);
      }

      &:active:not([loading]) {
        transform: translateY(0);
      }
    }
  }
}
</style>
